var apiurl = "http://app.weiduniang.com/api.php?callback=?";
;(function(root, factory) {
    var EasyApp = factory(root);
    if (typeof define === 'function' ) {
        // AMD
        define('EasyApp', function() {
            return EasyApp;
        });
    } else if (typeof exports === 'object') {
        // Node.js
        module.exports = EasyApp;
    } else {
        // Browser globals
        var _EasyApp = root.EasyApp;
        var _$ = root.$;
        EasyApp.noConflict = function(deep) {
            if (deep && root.EasyApp === EasyApp) {
                root.EasyApp = _EasyApp;
            }
            if (root.$ === EasyApp) root.$ = _$;
            return EasyApp;
        };
        root.EasyApp = root.$ = EasyApp;
    }
}(this, function(root, undefined) {
    "use strict";
    var emptyArray = [],slice = emptyArray.slice,filter = emptyArray.filter,some = emptyArray.some,elementTypes = [1, 9, 11],P={},u = {}, isAndroid = (/android/gi).test(navigator.appVersion),
    EasyApp = (function(){
        var EasyApp = function( selector ) {
            return new EasyApp.fn.init(selector);
        };
        EasyApp.fn = EasyApp.prototype = {
            init:function( selector ){
                var dom ;
                if (!selector)
                    dom = emptyArray,dom.selector = selector || '',dom.__proto__ = EasyApp.fn.init.prototype;
                else if (typeof selector == 'string' && (selector = selector.trim()) && selector[0] == '<'  && /^\s*<(\w+|!)[^>]*>/.test(selector))
                    dom = P.fragment(selector),selector=null;
                else if (EasyApp.isFunction(selector)) return EasyApp(document).ready(selector)
                else {
                    if (EasyApp.isArray(selector))
                        dom = selector;
                    else if (EasyApp.isObject(selector))
                        dom = [selector], selector = null
                    else if (elementTypes.indexOf(selector.nodeType) >= 0 || selector === window)
                        dom = [selector], selector = null;
                    else dom = (function(){
                        var found;
                        return (document && /^#([\w-]+)$/.test(selector))?
                        ((found = document.getElementById(RegExp.$1)) ? [found] : [] ):
                        slice.call(
                            /^\.([\w-]+)$/.test(selector) ? document.getElementsByClassName(RegExp.$1) :
                            /^[\w-]+$/.test(selector) ? document.getElementsByTagName(selector) :
                            document.querySelectorAll(selector)
                        );
                    })();
                }
                dom = dom || emptyArray;
                EasyApp.extend(dom, EasyApp.fn);
                dom.selector = selector || '';
                return dom;
            },
            size:function(){return this.length;}
        }
        EasyApp.fn.init.prototype = EasyApp.fn;
        EasyApp.extend = EasyApp.fn.extend = function () {
            var options, name, src, copy,
            target = arguments[0],i = 1,
            length = arguments.length,
            deep = false;
            //处理深拷贝的情况
            if (typeof (target) === "boolean")
                deep = target,target = arguments[1] || {},i = 2;
            //处理时，目标是一个字符串或（深拷贝可能的情况下）的东西
            if (typeof (target) !== "object" && !EasyApp.isFunction(target))
                target = {};
            //扩展EasyApp的本身，如果只有一个参数传递
            if (length === i) target = this,--i;
            for (; i < length; i++) {
                if ((options = arguments[i]) != null) {
                    for (name in options) {
                        src = target[name],copy = options[name];
                        if (target === copy) continue;
                        if (copy !== undefined) target[name] = copy;
                    }
                }
            }
            return target;
        };
        return EasyApp;
    })();

    EasyApp.fn.extend({
        forEach: emptyArray.forEach,
        concat: emptyArray.concat,
        indexOf: emptyArray.indexOf,
        ready: function(callback){
            if (EasyApp.isMobile()) {
                if (/complete|loaded|interactive/.test(document.readyState) && document.body){
                    window.apiready = callback;
                }
                else document.addEventListener('DOMContentLoaded', function(){
                    window.apiready = callback;
                }, false)
                return window.apiready;
            }else{
                if (/complete|loaded|interactive/.test(document.readyState) && document.body) callback(EasyApp)
                else document.addEventListener('DOMContentLoaded', function(){callback(EasyApp) }, false)
            }

            return this
        },
        each: function(callback){
            return EasyApp.each(this,callback);
        },
        map: function(fn){
            return EasyApp(EasyApp.map(this, function(el, i){ return fn.call(el, i, el) }));
        },
        // get: function(index){
        //     return index === undefined ? slice.call(this) : this[index >= 0 ? index : index + this.length];
        // },
        index: function(element){
            return element ? this.indexOf(EasyApp(element)[0]) : this.parent().children().indexOf(this[0])
        },
        empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
        detach: function(){return this.remove();},
        remove: function(){
            return this.each(function(){
                if (this.parentNode != null) this.parentNode.removeChild(this)
            })
        },
        text: function(text){
            return text === undefined ?
                (this.length > 0 ? this[0].textContent : null) :
                this.each(function(){this.textContent = funcArg(this, text)});
        },
        html:function(html){
            return 0 in arguments ? this.each(function(idx){
                EasyApp(this).empty().append(funcArg(this, html))
            }) : (0 in this ? this[0].innerHTML : null)
        },
        val:function(value){
            return 0 in arguments ?
            this.each(function(idx){this.value = funcArg(this, value, idx, this.value)}) :
            (this[0] && (this[0].multiple ?
                EasyApp(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
                this[0].value))
        },
        css:function(property, value){
            if (!this[0]) return [];
            var computedStyle = getComputedStyle(this[0], '')
            if(value === undefined && typeof property == 'string') return computedStyle.getPropertyValue(property);
            var css="",k;
            for(k in property) css += k+':'+property[k]+';';
            if(typeof property == 'string') css = property+":"+value;
            return this.each(function(el){
                css ? this.style.cssText += ';' + css :"";
            });
        },
        hide:function(){ return this.css("display", "none")},
        show:function(){
            return this.each(function(){
                this.style.display == "none" && (this.style.display = '');
                var CurrentStyle = function(e){
                    return e.currentStyle || document.defaultView.getComputedStyle(e, null);
                }
                function defaultDisplay(nodeName) {
                    var elm=document.createElement(nodeName),display
                    EasyApp('body').append(EasyApp(elm));
                    display = CurrentStyle(elm)['display'];
                    elm.parentNode.removeChild(elm)
                    return display
                }
                if (CurrentStyle(this)['display']=='none') {
                    this.style.display = defaultDisplay(this.nodeName)
                }
            })
        },
        toggle:function(setting){
            return this.each(function(){
                var el = $(this);(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
            })
        },
        offset:function(){
            if(this.length==0) return null;
            var obj = this[0].getBoundingClientRect();
            return {
                left: obj.left + window.pageXOffset,
                top: obj.top + window.pageYOffset,
                width: obj.width,
                height: obj.height
            };
        },
        attr: function(name,value){
            var result,k;
            return (typeof name == 'string' && !(1 in arguments)) ?
                (!this.length || this[0].nodeType !== 1 ? undefined :
                    (!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result
                ) : this.each(function(n){
                    if (EasyApp.isObject(name)) for(k in name) this.setAttribute(k, name[k]);
                    else this.setAttribute(name,funcArg(this, value));
                });
        },
        removeAttr:function(name){
            return this.each(function(){ this.nodeType === 1 && this.removeAttribute(name)});
        },
        hasClass:function(name){
            if (!name) return false
            return emptyArray.some.call(this, function(el){
                return this.test(el.className)
            }, new RegExp('(^|\\s)' + name + '(\\s|$)'));
        },
        addClass:function(name){
            if (!name) return this;
            var classList,cls,newName;
            return this.each(function(idx){
                classList=[],cls = this.className,newName=funcArg(this, name).trim();
                newName.split(/\s+/).forEach(function(k){
                    if (!EasyApp(this).hasClass(k)) classList.push(k);
                },this);
                if (!newName) return this;
                classList.length ? this.className = cls + (cls ? " " : "") + classList.join(" "):null;
            })
        },
        removeClass:function(name){
            var cls;
            if (name === undefined) return this.removeAttr('class');
            return this.each(function(idx){
                cls = this.className;
                funcArg(this, name, idx, cls).split(/\s+/).forEach(function(k){
                    cls=cls.replace(new RegExp('(^|\\s)'+k+'(\\s|$)')," ").trim();
                },this);
                cls?this.className = cls:this.className = "";
            })
        },
        toggleClass:function(name){
            if(!name) return this;
            return this.each(function(idx){
                var w=EasyApp(this),names=funcArg(this, name);
                names.split(/\s+/g).forEach(function(cls){
                    w.hasClass(cls)?w.removeClass(cls):w.addClass(cls);
                })
            })
        },
        filter:function(selector){
            if (EasyApp.isFunction(selector)) return this.not(this.not(selector))
            return EasyApp(filter.call(this, function(element){
                return EasyApp.matches(element, selector)
            }))
        },
        is: function(selector){
            if (this.length > 0 && EasyApp.isObject(selector)) return this.indexOf(selector)>-1?true:false;
            return this.length > 0 && EasyApp.matches(this[0], selector);
        },
        not:function(selector){
            var nodes = [];
            if (EasyApp.isFunction(selector)&& selector.call !== undefined){
                this.each(function(idx){
                    if (!selector.call(this,idx)) nodes.push(this);
                });
            }else {
                var excludes = typeof selector == 'string' ? this.filter(selector):
                (EasyApp.likeArray(selector) && EasyApp.isFunction(selector.item)) ? slice.call(selector) : EasyApp(selector)
                this.forEach(function(el){
                    if (excludes.indexOf(el) < 0) nodes.push(el)
                })
            }
            return EasyApp(nodes)
        },
        pluck: function(property){ return EasyApp.map(this, function(el){ return el[property] })},
        find: function(selector){
            var nodes = this.children(),ancestors=[];
            while (nodes.length > 0)
            nodes=EasyApp.map(nodes, function(node,inx){
                if (ancestors.indexOf(node)<0) ancestors.push(node);
                if ((nodes = EasyApp(node).children())&&nodes.length>0 ) return nodes;
            });
            return EasyApp(ancestors).filter(selector || '*');
        },
        clone: function(){return this.map(function(){ return this.cloneNode(true)})},
        add: function(selector){return EasyApp.unique(this.concat($(selector)));},
        eq: function(idx){return idx === -1 ? EasyApp(this.slice(idx)) : EasyApp(this.slice(idx, + idx + 1))},
        children:function(selector){
            var e=[];
            filter.call(this.pluck('children'), function(item, idx){
                EasyApp.map(item,function(els){ if (els&&els.nodeType == 1) e.push(els) })
            });
            return EasyApp(e).filter(selector || '*');
        },
        contents: function() {
            return this.map(function() { return this.contentDocument || slice.call(this.childNodes) })
        },
        parent: function(selector){return EasyApp(EasyApp.unique(this.pluck('parentNode'))).filter(selector||'*')},
        parents: function(selector){
            var ancestors=EasyApp.sibling(this,'parentNode');
            return selector == null ? EasyApp(ancestors) : EasyApp(ancestors).filter(selector);
        },
        closest: function(selector, context){
            var node = this[0], collection = false
            if (typeof selector == 'object') collection = EasyApp(selector)
            while (node && !(collection ? collection.indexOf(node) >= 0 : EasyApp.matches(node, selector)))
                node = node !== context && !EasyApp.isDocument(node) && node.parentNode
            return EasyApp(node)
        },
        slice:function(argument) { return EasyApp(slice.apply(this, arguments))},
        prev: function(selector){
            return EasyApp(this.pluck('previousElementSibling')).filter(selector || '*')
        },
        next: function(selector){
            return EasyApp(this.pluck('nextElementSibling')).filter(selector || '*')
        },
        nextAll: function (selector) {
            return EasyApp(EasyApp.sibling(this,'nextElementSibling')).filter(selector || '*');
        },
        prevAll: function (selector) {
            return EasyApp(EasyApp.sibling(this,'previousElementSibling')).filter(selector || '*');
        },
        siblings: function(selector){
            var n=[];this.map(function(i,el){
                filter.call(el.parentNode.children, function(els, idx){
                     if (els&&els.nodeType == 1&&els!=el) n.push(els)
                });
            })
            return EasyApp(n).filter(selector || '*');
        }
    });
    EasyApp.extend({
        fixIos7Bar : function(el){
            if(!EasyApp.isElement(el)){
                console.warn('$api.fixIos7Bar Function need el param, el param must be DOM Element');
                return;
            }
            var strDM = api.systemType;
            if (strDM == 'ios') {
                var strSV = api.systemVersion;
                var numSV = parseInt(strSV,10);
                var fullScreen = api.fullScreen;
                var iOS7StatusBarAppearance = api.iOS7StatusBarAppearance;
                if (numSV >= 7 && !fullScreen && iOS7StatusBarAppearance) {
                    el.style.paddingTop = '20px';
                }
            }
        },
        fixStatusBar : function(el){
            if(!EasyApp.isElement(el)){
                console.warn('$api.fixStatusBar Function need el param, el param must be DOM Element');
                return;
            }
            var sysType = api.systemType;
            if(sysType == 'ios'){
                EasyApp.fixIos7Bar(el);
            }else if(sysType == 'android'){
                var ver = api.systemVersion;
                ver = parseFloat(ver);
                if(ver >= 4.4){
                    el.style.paddingTop = '25px';
                }
            }
        },
        alert:function(msg){
            window.alert(msg);
        },
        toast : function(title, text, time){
            var opts = {};
            var show = function(opts, time){
                api.showProgress(opts);
                setTimeout(function(){
                    api.hideProgress();
                },time);
            };
            if(arguments.length === 1){
                var time = time || 500;
                if(typeof title === 'number'){
                    time = title;
                }else{
                    opts.title = title+'';
                }
                show(opts, time);
            }else if(arguments.length === 2){
                var time = time || 500;
                var text = text;
                if(typeof text === "number"){
                    var tmp = text;
                    time = tmp;
                    text = null;
                }
                if(title){
                    opts.title = title;
                }
                if(text){
                    opts.text = text;
                }
                show(opts, time);
            }
            if(title){
                opts.title = title;
            }
            if(text){
                opts.text = text;
            }
            time = time || 500;
            show(opts, time);
        },
        isElement : function(obj){
            return !!(obj && obj.nodeType == 1);
        },
        isMobile:function(){
            var u = navigator.userAgent, app = navigator.appVersion;
            return !!u.match(/AppleWebKit.*Mobile.*/)||!!u.match(/AppleWebKit/);
        },
        isPhoneNumber:function(tel){
             var reg = /^0?1[3|4|5|8][0-9]\d{8}$/;
             return reg.test(tel)
        },
        uzStorage : function(){
            var ls = window.localStorage;
            if(isAndroid){
               ls = os.localStorage();
            }
            return ls;
        },
        setStorage : function(key, value){
            // if (!EasyApp.isMobile()) return "";
            if(arguments.length === 2){
                var v = value;
                if(typeof v == 'object'){
                    v = JSON.stringify(v);
                    v = 'obj-'+ v;
                }else{
                    v = 'str-'+ v;
                }
                var ls = EasyApp.uzStorage();
                if(ls){
                    ls.setItem(key, v);
                }
            }
        },
        getStorage : function(key){
            var ls = EasyApp.uzStorage();
            if(ls){
                var v = ls.getItem(key);
                if(!v){return;}
                if(v.indexOf('obj-') === 0){
                    v = v.slice(4);
                    return JSON.parse(v);
                }else if(v.indexOf('str-') === 0){
                    return v.slice(4);
                }
            }
            return "";
        },
        rmStorage : function(key){
            var ls = EasyApp.uzStorage();
            if(ls && key){
                ls.removeItem(key);
            }
        },
        clearStorage : function(){
            var ls = EasyApp.uzStorage();
            if(ls){
                ls.clear();
            }
        },
        getApi:function (arg,arg_val,url){
            if (!url) url = apiurl;
            var pattern=arg+'=([^&]*)';
            var replaceText=arg+'='+arg_val;
            if(url.match(pattern)){
                var tmp='/('+ arg+'=)([^&]*)/gi';
                tmp=url.replace(eval(tmp),replaceText);
                return tmp;
            }else{
                if(url.match('[\?]')){
                    return url+'&'+replaceText;
                }else{
                    return url+'?'+replaceText;
                }
            }
            return url+'\n'+arg+'\n'+arg_val;
        },
        ckLoginApi:function(apid){
            var apiurl = EasyApp.getApi('apid',apid);
            apiurl = EasyApp.getApi('c','User',apiurl);
            apiurl = EasyApp.getApi('a','ckLogin',apiurl);
            return apiurl;
        },
        ckRegApi:function(apid){
            var apiurl = EasyApp.getApi('apid',apid);
            apiurl = EasyApp.getApi('c','User',apiurl);
            apiurl = EasyApp.getApi('a','ckReg',apiurl);
            return apiurl;
        },
        App:function(){
            var app = EasyApp.getStorage('appinfo');
            if (app) {
                return app;
            }else{
                EasyApp.alert('获取应用信息失败');
            }
        },
        User:function(){
            var user = EasyApp.getStorage('User');
            if (user) {
                return user;
            }else{
                EasyApp.alert('获取用户信息失败');
            }
        },
        getApp : function (apid,func){
            var ap = EasyApp.getStorage('appinfo');
            if (ap) {
                func(ap);
                return;
            }
            if (!apid) {
                EasyApp.alert('获取应用信息失败');
                return ;
            };
            var apiurl = EasyApp.getApi('apid',apid);
            apiurl = EasyApp.getApi('c','Apps',apiurl);
            EasyApp.get(apiurl,function(req){
                if (req) {
                    EasyApp.setStorage('appinfo',req);
                    func(req);
                };
            });
        },

        getPageList : function (apid,func){
            var apiurl = EasyApp.getApi('apid',apid);
            apiurl = EasyApp.getApi('c','Page',apiurl);
            apiurl = EasyApp.getApi('a','getAllPages',apiurl);
            EasyApp.get(apiurl,function(req){
                if (req) {
                    func(req);
                };
            });
        },

        getContentList : function (apid,pageid,func){
            var apiurl = EasyApp.getApi('apid',apid);
            apiurl = EasyApp.getApi('c','Content',apiurl);
            apiurl = EasyApp.getApi('a','getList',apiurl);
            apiurl = EasyApp.getApi('pageid',pageid,apiurl);
            EasyApp.get(apiurl,function(req){
                if (req) {
                    func(req);
                };
            });
        },

        getContent : function (apid,id,func){
            var apiurl = EasyApp.getApi('id',id);
            apiurl = EasyApp.getApi('apid',apid,apiurl);
            apiurl = EasyApp.getApi('c','Content',apiurl);
            EasyApp.get(apiurl,function(req){
                if (req) {
                    func(req);
                };
            });
        },

        openWin : function (url,name,cfg){

            if (!EasyApp.isMobile()) {
                window.location.href = url;
                return false;
            }

            var parArr = {},
            parArr = EasyApp.UrlParamToArray(url);
            var delay = 0;
            if("ios" != api.systemType){
                delay = 300;
            }

            var set = {
                name: name,
                url: url,
                pageParam: parArr,
                bounces: false,
                vScrollBarEnabled:true,
                hScrollBarEnabled:false,
                reload: true,
                delay: delay
            }

            if (cfg) EasyApp.extend(set, cfg); 
            api.openWin(set);
        },
        redirect:function(url,pars){
            if (!EasyApp.isMobile()) {
                window.location.href = url;
                return;
            };

            var delay = 0;
            if("ios" != api.systemType){
                delay = 300;
            }
            api.openWin({
                name: "sort",
                url: url,
                pageParam: pars,
                bounces: false,
                vScrollBarEnabled:false,
                hScrollBarEnabled:false,
                reload: true,
                delay: delay
            });
        },
    })

    EasyApp.extend({

        isDocument:function (obj) { return obj = obj ? obj != null && obj.nodeType ? obj.nodeType == obj.DOCUMENT_NODE : false : undefined;},
        isFunction:function (value) { return ({}).toString.call(value) == "[object Function]" },
        isObject:function (value) { return value instanceof Object },
        isArray:function (value) { return value instanceof Array },
        isString:function(obj){ return typeof obj == 'string' },
        isWindow:function(obj){ return obj != null && obj == obj.window },
        isPlainObject:function(obj){
            return this.isObject(obj) && !this.isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
        },
        isJson: function (obj) {
            var isjson = typeof(obj) == "object" &&
            Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
            return isjson;
        },
        parseJSON:JSON.parse,
        likeArray:function (obj) {return obj? typeof obj.length == 'number' :null },
        type: function (obj) {
            if(!obj) return undefined;
            var type="";
            EasyApp.each("Boolean Number HTMLDivElement String Function Array Date RegExp Object Error".split(" "), function(i, name) {
                if(Object.prototype.toString.call(obj).indexOf(name) > -1) type = name == "HTMLDivElement"?"Object":name;
            })
            return type;
        },
        trim:function(str){if(str) return str.trim();},
        intersect:function(a,b){
            var array=[];
            a.forEach(function(item){
                if(b.indexOf(item)>-1) array.push(item);
            })
            return array;
        },
        error:function(msg) {throw msg;},
        getUrlParam:function (name,is) {
            if (EasyApp.isMobile() && is != 'web') {
                var pageParam = api.pageParam
                return pageParam[name];
            };
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"),
            r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        },
        UrlParamToArray:function(url){
            if (!url) url = window.location.href;
            var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
            var paraObj = {} ;
            var j = 0,i=0;
            for (i=0; j=paraString[i]; i++){
                paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);    
            }
            return paraObj;
        },
        each:function(elements, callback){
            var i, key
            if (this.likeArray(elements)) {
                for (i = 0; i < elements.length; i++)
                    if (callback.call(elements[i], i, elements[i]) === false) return elements
                } else {
                for (key in elements)
                    if (callback.call(elements[key], key, elements[key]) === false) return elements
            }
            return elements
        },
        map:function(elements, callback){
            var value, values = [], i, key
            if (this.likeArray(elements)) for (i = 0; i < elements.length; i++) {
                value = callback(elements[i], i)
                if (value != null) values.push(value)
            }
            else for (key in elements) {
                value = callback(elements[key], key)
                if (value != null) values.push(value)
             }
            return values.length > 0 ? EasyApp.fn.concat.apply([], values) : values;
        },
        grep:function(elements, callback){
            return filter.call(elements, callback)
        },
        matches:function(element, selector){
            if (!selector || !element || element.nodeType !== 1) return false;
            var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
                                element.oMatchesSelector || element.msMatchesSelector || element.matchesSelector;
            if (matchesSelector) return matchesSelector.call(element, selector);
        },
        unique:function(array){return filter.call(array, function(item, idx){ return array.indexOf(item) == idx })},
        inArray:function(elem, array, i){
            return emptyArray.indexOf.call(array, elem, i)
        },
        sibling:function(nodes,ty){
            var ancestors = [];
            while (nodes.length > 0)
            nodes = EasyApp.map(nodes, function(node){
                if ((node = node[ty]) && !EasyApp.isDocument(node) && ancestors.indexOf(node) < 0)
                    ancestors.push(node)
                    return node
            });
            return ancestors;
        },
        contains:function(parent, node){
            if(parent&&!node) return document.documentElement.contains(parent)
            return parent !== node && parent.contains(node)
        }
    });

    P = {
        singleTagRE:/^<(\w+)\s*\/?>(?:<\/\1>|)$/,
        fragmentRE:/^\s*<(\w+|!)[^>]*>/,
        tagExpanderRE:/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
        table: document.createElement('table'),
        tableRow: document.createElement('tr'),
        containers:{
            '*': document.createElement('div'),
            'tr': document.createElement('tbody'),
            'tbody': P.table,'thead': P.table,'tfoot': P.table,
            'td': P.tableRow,'th': P.tableRow
        },
        fragment:function(html,name){
            var dom, container
            if (this.singleTagRE.test(html)) dom = EasyApp(document.createElement(RegExp.$1));
            if (!dom) {
                if (html.replace) html = html.replace(this.tagExpanderRE, "<$1></$2>")
                if (name === undefined) name = this.fragmentRE.test(html) && RegExp.$1
                if (!(name in this.containers)) name = '*'
                container = this.containers[name]
                container.innerHTML = '' + html
                dom = EasyApp.each(slice.call(container.childNodes), function(){
                    container.removeChild(this)
                });
            }
            return dom;
        }
    };
    ;['width', 'height'].forEach(function(dimension){
        var dimensionProperty = dimension.replace(/./,dimension[0].toUpperCase())
        EasyApp.fn[dimension]=function(value){
            var offset, el = this[0]
            if (value === undefined) return EasyApp.isWindow(el) ? el['inner' + dimensionProperty] :
            EasyApp.isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
            (offset = this.offset()) && offset[dimension]
            else return this.each(function(idx){
                el = $(this)
                el.css(dimension, funcArg(this, value, idx, el[dimension]()))
            })
        }
    })
    ;['after','prepend','before','append'].forEach(function(operator, operatorIndex) {
        var inside = operatorIndex % 2;
        EasyApp.fn[operator] = function(){
            var argType, nodes = EasyApp.map(arguments, function(arg) {
                    argType = EasyApp.type(arg)
                    if(argType=="Function") arg = funcArg(this, arg)
                    return argType == "Object" || argType == "Array" || arg == null ? arg : P.fragment(arg)
                }),parent,script,copyByClone = this.length > 1
            if (nodes.length < 1) return this
            return this.each(function(_, target){
                parent = inside ? target : target.parentNode
                target = operatorIndex == 0 ? target.nextSibling :
                        operatorIndex == 1 ? target.firstChild :
                        operatorIndex == 2 ? target :
                        null;

                var parentInDocument = EasyApp.contains(document.documentElement, parent)

                nodes.forEach(function(node){
                    var txt
                    if (copyByClone) node = node.cloneNode(true)
                    parent.insertBefore(node, target);
                    if(parentInDocument && node.nodeName != null && node.nodeName.toUpperCase() === 'SCRIPT' &&
                        (!node.type || node.type === 'text/javascript') && !node.src) txt=node.innerHTML;
                    else if(parentInDocument &&node.children && node.children.length>0&&EasyApp(node)&&(script=EasyApp(node).find("script")))
                        if(script.length>0) script.each(function(_,item){
                            txt=item.innerHTML
                        });
                        txt?window['eval'].call(window, txt):undefined;
                });
            })
        }
        EasyApp.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
            EasyApp(html)[operator](this)
            return this
        }
    });

    function parseArguments(url, data, success, dataType){
        EasyApp.isFunction(data) && (dataType = success, success = data, data = undefined),
        EasyApp.isFunction(success) || (dataType = success, success = undefined)
        return {
            url: url,
            data: data,
            success: success,
            dataType: dataType
        }
    }


        var handlers = {},_jid = 1
        /* 绑定事件 start */
        EasyApp.fn.extend({
            bind: function(event, func) {return this.each(function(){add(this, event, func)})},
            unbind:function(event, func) {return this.each(function(){remove(this, event, func)})},
            on:function(event, selector, data, callback){
                var self = this
                if (event && !EasyApp.isString(event)) {
                    EasyApp.each(event, function(type, fn){
                        self.on(type, selector, data, fn)
                    })
                    return self
                }
                if (!EasyApp.isString(selector) && !EasyApp.isFunction(callback) && callback !== false)
                    callback = data, data = selector, selector = undefined
                if (EasyApp.isFunction(data) || data === false)
                    callback = data, data = undefined
                if (callback === false) callback = function(){return false;}
                return this.each(function(){ 
                    add(this, event, callback, data, selector) 
                })
            },
            off:function(event, selector, callback){
                var self = this
                if (event && !EasyApp.isString(event)) {
                    EasyApp.each(event, function(type, fn){
                        self.off(type, selector, fn)
                    })
                    return self
                }
                if (!EasyApp.isString(selector) && !EasyApp.isFunction(callback) && callback !== false)
                    callback = selector, selector = undefined
                if (callback === false) callback =  function(){return false;}
                return self.each(function(){
                    remove(this, event, callback, selector)
                })
            },
            delegate: function(selector, event, callback){
                return this.on(event, selector, callback)
            },
            trigger:function(event, data){
                var type = event,specialEvents={}
                specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents';
                if (typeof type == 'string') {
                    event = document.createEvent(specialEvents[type] || 'Events');
                    event.initEvent(type,true, true);
                }else return;
                event._data = data;
                return this.each(function(){
                    if('dispatchEvent' in this) this.dispatchEvent(event);
                });
            }
        });
        EasyApp.event={add:add,remove:remove};
        function add(element, events, func, data, selector){
            var self=this,id=jid(element),set=(handlers[id] || (handlers[id] = []));
            events.split(/\s/).forEach(function(event){
                var handler = EasyApp.extend(parse(event), {fn: func,sel: selector, i: set.length});
                var proxyfn = handler.proxy = function (e) {
                    //处理事件代理
                    if (selector) {
                        var $temp = $(element).find(selector);
                        var res = some.call($temp, function(val) {
                            return val === e.target || EasyApp.contains(val, e.target);
                        });
                        //不包含
                        if (!res) {
                            return false;
                        }
                    }
                    e.data = data;
                    var result = func.apply(element,e._data == undefined ? [e] : [e].concat(e._data));
                    if (result === false) e.preventDefault(), e.stopPropagation();
                    return result;
                };
                set.push(handler)
                if (element.addEventListener) element.addEventListener(handler.e,proxyfn, false);
            })
        }
        function remove(element, events, func, selector){
            ;(events || '').split(/\s/).forEach(function(event){
                EasyApp.event = parse(event)
                findHandlers(element, event, func, selector).forEach(function(handler){
                    delete handlers[jid(element)][handler.i]
                    if (element.removeEventListener) element.removeEventListener(handler.e, handler.proxy, false);
                })
            })
        }
        function jid(element) {return element._jid || (element._jid = _jid++)}
        function parse(event) {
            var parts = ('' + event).split('.');
            return {e: parts[0], ns: parts.slice(1).sort().join(' ')};
        }
        function findHandlers(element, event, func, selector){
            var self=this,id = jid(element);event = parse(event)
            return (handlers[jid(element)] || []).filter(function(handler) {
                return handler 
                && (!event.e  || handler.e == event.e) 
                && (!func || handler.fn.toString()===func.toString())
                && (!selector || handler.sel == selector);
            })
        }
        ;("blur focus focusin focusout load resize scroll unload click dblclick " +
        "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
        "change select submit keydown keypress keyup error paste drop dragstart dragover " +
        "beforeunload").split(' ').forEach(function(event) {
            EasyApp.fn[event] = function(callback) {
                return callback ? this.bind(event, callback) : this.trigger(event);
            }
        });


    EasyApp.extend({
        ajaxSettings:{
            // 默认请求类型
            type:'GET',
            // 如果请求成功时执行回调
            success:function(){},
            // 如果请求失败时执行回调
            error:function(){},
            xhr:function () {
              return new window.XMLHttpRequest();
            },
            processData: !0,
            async:!0,
            complete:function(){},//要求执行回调完整（包括：错误和成功）
            // MIME类型的映射
            accepts:{
                script:'text/javascript, application/javascript',
                json:  'application/json',
                xml:   'application/xml, text/xml',
                html:  'text/html',
                text:  'text/plain'
            }
        },
        param:function(obj,traditional,scope){
            if(EasyApp.type(obj) == "String") return obj;
            var params = [],str='';
            params.add=function(key, value){
                this.push(encodeURIComponent(key) + '=' + encodeURIComponent(value== null?"":value))
            };
            if(scope==true&&EasyApp.type(obj)=='Object') params.add(traditional,obj)
            else {
                for(var p in obj) {
                    var v = obj[p],str='',
                        k = (function(){
                            if (traditional) {
                                if (traditional==true) return p;
                                else{
                                    if(scope&&EasyApp.type(obj)=='Array'){
                                        return traditional
                                    }
                                    return traditional + "[" + (EasyApp.type(obj)=='Array'?"":p) + "]";
                                };
                            };
                            return p
                        })();
                    if (typeof v=="object") {
                        str=this.param(v, k ,traditional);
                    }else str=params.add(k,v);

                    if (str) params.push(str);
                };
            }
            return params.join('&');
        },
        get:function(url, success){
            var options = parseArguments.apply(null, arguments);
            return options.type = "GET", EasyApp.ajax(options);
        },
        post:function(url, data, success, dataType){
            var options = parseArguments.apply(null, arguments);
            if (EasyApp.isMobile()) {
                return options.type = "POST", EasyApp.ajax(options);

            }else{
                return options.type = "GET", EasyApp.ajax(options);

            }
        },
        getJSONP: function(url, data, func) {
            // 函数名称
            var name,t = (new Date()).getTime(),r=Math.random().toString().substr(2);

            if (data){

                data?url =(url.indexOf('?')>-1?url +'&'+ data:url +'?'+ data) :null;
            }

            // 检测callback的函数名是否已经定义
            var match = /callback=(\w+)/.exec(url);
            if (match && match[1]) {
                name = match[1];
            } else {
                // 如果未定义函数名的话随机成一个函数名
                // 随机生成的函数名通过时间戳拼16位随机数的方式，重名的概率基本为0
                // 如:jsonp_1355750852040_8260732076596469
                name = "jsonp_" + t + '_' + r;
                // 把callback中的?替换成函数名
                url = url.replace("callback=?", "callback=" + name);
                // 处理?被encode的情况
                url = url.replace("callback=%3F", "callback=" + name);
            }

            // 创建一个script元素
            var script = document.createElement("script");
            script.type = "text/javascript";
            // 设置要远程的url
            script.src = url;
            // 设置id，为了后面可以删除这个元素
            script.id = "id_" + name;
            // 把传进来的函数重新组装，并把它设置为全局函数，远程就是调用这个函数
            window[name] = function(json) {
                // 执行这个函数后，要销毁这个函数
                window[name] = undefined;
                // 获取这个script的元素
                var elem = document.getElementById("id_" + name);
                // 删除head里面插入的script，这三步都是为了不影响污染整个DOM啊
                EasyApp(elem).remove();
                // 执行传入的的函数
                func(json);
            };

            // 在head里面插入script元素
            var head = document.getElementsByTagName("head");
            if (head && head[0]) {
                head[0].appendChild(script);
            }
        },

        apiAjax : function(settings){
            var json = {};
            var fnSuc = settings.success;
            settings.url && (json.url = settings.url.replace("callback",'nocallback'));
            if (settings.type.toUpperCase() == 'GET') {
                settings.data && (json.data = settings.data);
            }
            if(settings.dataType){
                var type = settings.dataType.toLowerCase();
                if (type == 'text'||type == 'json') {
                    json.dataType = type;
                }
            }else{
                json.dataType = 'json';
            }
            if (json.dataType == 'jsonp') json.dataType = "json";
            json.method = settings.type.toLowerCase();
            // alert(json.url);
            api.ajax(json,
                function(ret,err){
                    if (ret) {
                        fnSuc && fnSuc(ret);
                    }
                }
            );
        },

        ajax:function(options){
            var key,settings,
                setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
                appendQuery = function(url, query) {
                    if (query == '') return url
                    return (url + '&' + query).replace(/[&?]{1,2}/, '?')
                },
                serializeData = function(options){
                    if (options.processData && options.data && EasyApp.type(options.data) != "string")
                        options.data = EasyApp.param(options.data, options.traditional)
                    if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
                        options.url = appendQuery(options.url, options.data), options.data = undefined
                };
                options = options || {};
                if (EasyApp.isString(options)) {
                    if (arguments[0]=="GET") {
                        var  urls=arguments[1];
                        if (arguments[2]&&EasyApp.isFunction(arguments[2])) {
                            EasyApp.get(urls,arguments[2])
                        }else if(arguments[2]&&EasyApp.isJson(arguments[2])){
                            EasyApp.get(urls.indexOf('?')>-1?urls+'&'+this.param(arguments[2]):urls+'?'+this.param(arguments[2]),arguments[3])
                        };
                    }else if(arguments[0]=="POST"){
                        EasyApp.post(arguments[1],arguments[2],arguments[3],arguments[4])
                    };
                    return;
                };
                settings=EasyApp.extend({}, options || {});
                for (key in EasyApp.ajaxSettings) if (settings[key] === undefined) settings[key] = EasyApp.ajaxSettings[key];
                //{ type, url, data, success, dataType, contentType }
            serializeData(settings);
            if (EasyApp.isMobile()) {
                EasyApp.apiAjax(settings);
                return;
            }
            var dataType = settings.dataType,hasPlaceholder = /\?.+=\?/.test(settings.url) ;
            if (hasPlaceholder) dataType = 'jsonp';
            if ('jsonp' == dataType) {
                EasyApp.getJSONP(settings.url,settings.data,settings.success);
                return;
            }

            var data = settings.data,
                callback = settings.success || function(){},
                errback = settings.error || function(){},
                mime = EasyApp.ajaxSettings.accepts[settings.dataType],
                content = settings.contentType,
                xhr = new XMLHttpRequest(),
                nativeSetHeader = xhr.setRequestHeader,
                headers={};
                if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest'),setHeader('Accept', mime || '*/*');
                if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name]);
                if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
                    setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function(){
                if (xhr.readyState == 4) {
                    if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 0) {
                        if (mime == 'application/json'&&!(/^\s*$/.test(xhr.responseText))) {
                            var result, error = false;
                                result = xhr.responseText
                            try {
                                if (settings.dataType == 'script')    (1,eval)(result)
                                else if (settings.dataType == 'xml')  result = xhr.responseXML
                                else if (settings.dataType == 'json') result = /^\s*$/.test(result) ? null : JSON.parse(result)
                            } catch (e) { error = e }

                            if (error) errback(error, 'parsererror', xhr, settings);
                            else callback(result, 'success', xhr);
                        } else {
                            callback(xhr.responseText, 'success', xhr)
                        };
                    } else {
                        settings.complete(xhr, error ? 'error' : 'success')
                    }
                }
            };
            if (data&&data instanceof Object&&settings.type=='GET'){
                data?settings.url =(settings.url.indexOf('?')>-1?settings.url +'&'+ data:settings.url +'?'+ data) :null;
            }
            xhr.open(settings.type, settings.url, true);
            if (mime) xhr.setRequestHeader('Accept', mime);
            if (data instanceof Object && mime == 'application/json' ) data = JSON.stringify(data), content = content || 'application/json';
            for (name in headers) nativeSetHeader.apply(xhr, headers[name]);

            xhr.send(data?data:null);
        },

    });


    function funcArg(context, arg, idx, payload) {
        return EasyApp.isFunction(arg) ? arg.call(context, idx, payload) : arg;
    }
    //字符串处理
    EasyApp.extend(String.prototype,{
        trim: function () {return this.replace(/(^\s*)|(\s*$)/g, "");},
        leftTrim: function () {return this.replace(/(^\s*)/g, "");}
    });
    return EasyApp;
}));







